<template>
  <div class="body-form-account">
    <a-form
      :label-col-style="{ display: 'none' }"
      :wrapper-col-style="{ flex: 1 }"
      ref="formRef"
      :model="form"
      :rules="rules"
      @submit="phoneLogin"
    >
      <a-form-item field="mobile">
        <div class="input-icon">
          <GiSvgIcon name="phone-login" size="24"></GiSvgIcon>
        </div>
        <div class="line"></div>
        <a-input placeholder="请输入手机号" v-model.trim="form.mobile" :max-length="11" />
      </a-form-item>

      <div class="phone-code">
        <a-form-item class="phone-code-form" style="margin-bottom: 0" field="smsCode">
          <div class="input-icon">
            <GiSvgIcon name="mail-login" size="24"></GiSvgIcon>
          </div>
          <div class="line"></div>
          <a-input placeholder="验证码" v-model.trim="form.smsCode" :max-length="4"/>
        </a-form-item>
        <a-button class="phone-code-btn" @click="handelGetCode" :disabled="isGetCode">{{ codeBtn }}</a-button>
      </div>
      <a-button class="login-btn" html-type="submit">立即登录</a-button>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { useRouter } from "vue-router";
import { type FormInstance, Message } from "@arco-design/web-vue";
import { useLoading } from "@/hooks";
import { useUserStore } from "@/stores";
import { getVerifyCode } from "@/apis/user";
import * as Regexp from "@/utils/regexp";
import _ from "lodash"

const router = useRouter();
const userStore = useUserStore();
const { setLoading } = useLoading();
const form = ref({
  grantType: "sms",
  smsCode: "",
  mobile: ""
});
const rules: FormInstance["rules"] = {
  mobile: [
    { required: true, message: "请输入手机号码" },
    { match: Regexp.Phone, message: "手机号格式不正确" }
  ],
  smsCode: [
    { required: true, message: "请输入验证码" },
      { match: Regexp.Code_4, message: "请输入4位数字验证码" }
  ]
};

const codeBtn = ref("获取验证码");
const isGetCode = ref(false);
let timer:any = null;
let number = 60;
const getCode = async () => {
  await getVerifyCode({ mobile:form.value.mobile });
  timer && clearInterval(timer);
  isGetCode.value = true;
  timer = setInterval(() => {
    codeBtn.value = `重新发送${number--}s`;
    if (number === 0) {
      clearInterval(timer);
      timer = null;
      codeBtn.value = "获取验证码";
      isGetCode.value = false;
    }
  }, 1000);
};
const handelGetCode = _.debounce(getCode,500)

const formRef = ref<FormInstance>();
const accountLogin = async () => {
  const valid = await formRef.value?.validate();
  if (valid) return;
  await userStore.login(form.value);
  const { redirect, ...othersQuery } = router.currentRoute.value.query;
  router.push({
    path: "/",
    query: {
      ...othersQuery
    }
  });
  Message.success("登录成功");
};
const phoneLogin = _.debounce(accountLogin,500)

onUnmounted(() => {
  clearInterval(timer);
});
</script>

<style scoped lang="scss">
@import "index";
</style>
